<script lang="ts" setup>
  import { ref, onMounted, onUnmounted } from 'vue';
  import * as echarts from 'echarts/core';
  const props = defineProps({
    data1: { type: Object as () => any, required: true },
    datax: { type: Object as () => any, required: true },
  });

  const chartRef = ref<HTMLElement | null>(null);
  let chartInstance: echarts.ECharts | null = null;

  const option = {
    tooltip: {
      show: true,
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '5%',
      top: '10%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: props.datax,
      axisLine: {
        lineStyle: {
          color: '#fff', // 轴线颜色
          width: 1, // 轴线宽度
          type: 'solid', // 线型（solid实线，dashed虚线）
        },
      },
      splitLine: { show: false },
      axisLabel: { show: false }, // 隐藏 X 轴标签
    },
    yAxis: {
      type: 'value',
      splitLine: {
        show: false,
      },
      axisLabel: {
        color: '#fff',
      },
    },
    series: [
      {
        name: '板形',
        type: 'bar',
        barWidth: '70%',
        data: props.data1,
        itemStyle: {
          color: '#2eb7fb',
        },
      },
    ],
  };

  const initCharts = () => {
    try {
      option.series[0].data = props.data1 ?? [];
      option.xAxis.data = props.datax ?? [];
      if (chartRef.value && !chartInstance) {
        chartInstance = echarts.init(chartRef.value);
        chartInstance?.setOption(option, true);
      }
    } catch (error) {
      console.error('图表初始化失败:', error);
    }
  };

  const updateChart = () => {
    option.series[0].data = props.data1 ?? [];
    option.xAxis.data = props.datax ?? [];
    if (chartRef.value && chartInstance) {
      chartInstance.setOption(option, true);
    }
  };

  onMounted(() => {
    // 确保在 DOM 加载完成后更新图表
    setTimeout(() => {
      initCharts();
    }, 100);

    // 添加窗口大小变化监听
    window.addEventListener('resize', updateChart);
  });

  onUnmounted(() => {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', updateChart);
    chartInstance?.dispose();
  });

  watch(
    () => [props.datax, props.data1],
    () => updateChart(),
    { deep: true }
  );

  defineExpose({
    updateChart, // 暴露方法到父组件
    chartRef,
  });
</script>
<template>
  <div ref="chartRef" class="chart-container"></div>
</template>

<style scoped>
  .chart-container {
    width: 100%;
    height: 100%;
  }
</style>
